<template>
  <view class="container">
    <view style="height: 216rpx"></view>
    <view class="top_box">
      <!-- 搜索 -->
      <view class="search">
        <view class="search_box">
          <u-search clearabled :showAction="false" @clear="getGoodsOrderList()" @custom="getGoodsOrderList()"
            @search="searchOrderList" v-model="queryParam.queryTitle" placeholder="输入订单名称搜索"></u-search>
        </view>
        <view class="company_box_bottom" @click="myUser">
          <view class="iconfont red" style="font-size: 40rpx">&#xe61f;</view>
          <text class="text">我的</text>
        </view>
      </view>
      <!-- 标签栏 -->
      <TabBar ref="tabBar" :tabsList="tabList" @onClickItem="onClickTab"></TabBar>
    </view>
    <van-collapse :value="activeNames" @change="onChange">
      <van-collapse-item :is-link="false" :border="false" :key="item.id" :name="index + ''"
        :value="item.create_time | dateMimute" v-for="(item, index) in showGoodsOrderList">
        <view slot="title">
          <view class="count-down-box" v-if="item.children[0].state == 2">
            <view class="count-down__title">还剩：</view>
            <u-count-down autoStart millisecond :key="item.id" format="mm分ss秒" @finish="finish" :time="item.time">
            </u-count-down>
          </view>
          <!-- <view v-else>{{ item.company_id }}</view> -->
          <view v-else>{{ shopComName(item.company_id) }}</view>
        </view>
        <view :key="item2.id" class="goods_item_content_box" v-for="item2 in item.children"
          @click="toOrderDetail(item2.v_id)">
          <view class="img_box">
            <image lazy-load class="img" mode="aspectFill" :src="item2.images_kv"></image>
          </view>
          <view class="content_box">
            <view class="title">{{ item2.shop_title }}</view>
            <view class="coupon_box">
              <view class="server" v-if="item2.post_service == 1">包邮</view>
              <view class="post" v-if="(currIndex == 0 || currIndex == 1 || currIndex == 3) &&
                item2.post_service == 1 &&
                !logistics_no
                ">48小时内发货</view>
              <view class="server" v-if="item2.post_service == 3">到店领取</view>
              <view class="server" v-if="item2.post_service == 4">卡劵礼包</view>
              <view class="server" v-if="item2.state == 5">已退款</view>
              <view class="server" v-if="item2.state == 6">线下已付</view>
              <view class="post post__red" @click.stop="queryPostInfo(item2.logistics_no)" v-if="item2.post_service < 3 &&
                item2.logistics_no &&
                item2.logistics_no.length > 8
                ">查看物流</view>
              <view class="server-r" v-if="item2.post_service == 5">付寄</view>
              <view class="server-r" v-if="item2.post_service == 5">付寄</view>
            </view>
            <view class="bottom_box">
              <view class="price_box">
                <view class="present"><text v-if="item2.prepaid_price && item2.prepaid_price > 0">订金 </text>￥<text
                    class="price">{{
                      item2.price | moneyShow
                    }}</text></view>
              </view>
              <view class="num">x{{ item2.num }}</view>
            </view>
          </view>
        </view>
        <view class="order-bottom" :style="{
          'justify-content':
            item.children[0].state == 2 ? 'space-between' : 'flex-end'
        }">
          <view v-if="item.children[0].state == 2" @click.stop="deleteOrder(item.v_id)">
            删除
          </view>
          <view class="order-bottom__box">
            <view class="order-bottom__pay" v-if="item.children[0].state == 2" @click.stop="clickPay(item)">继续支付</view>
            <view class="order-bottom__total-price" v-if="currIndex != 3">订单总价：<text
                class="order-bottom__total-price__price">￥{{ item.price_paid | moneyShow }}</text></view>
          </view>
        </view>
      </van-collapse-item>
      <view class="order-bottom__count-down" v-if="item.children[0].state == 2">
        <view class="order-bottom__count-down__text">还剩: </view>
        <u-count-down :time="item.time" format="mm:ss"></u-count-down>
      </view>
      <!-- {{ item.time }} -->
    </van-collapse>
    <u-empty mode="search" text="没有搜索结果" v-if="!goodsOrderList.length"
      icon="https://www.kamlung.net/images/other/search1.png">
    </u-empty>
    <u-modal :show="showModal" title="物流信息" @confirm="showModal = false" confirmColor="#de4141">
      <view class="slot-content">
        <scroll-view scroll-y="true" class="scroll-Y">
          <u-steps current="1" direction="column" activeColor="#de4141" :dot="true">
            <u-steps-item :key="index" :title="item.state" :desc="item.date + ' - ' + item.time"
              v-for="(item, index) in logisticsInfo">
            </u-steps-item>
          </u-steps>
        </scroll-view>
      </view>
    </u-modal>
    <u-modal :show="delModal" showCancelButton confirmColor="#de4141" @cancel="delModal = false" @confirm="callDeleteApi"
      title="您确定要删除该订单吗?"></u-modal>
  </view>
</template>

<script>
let flag = true;
import {
  userPayApi,
  fastPieceApi,
  goodsOrderListApi,
  groupMyGoodsDelApi,
  getShopTypeCateListApi
} from '@/API/Shop'
import { mapMutations, mapState } from 'vuex'
import { tabList } from '@/static/js/staticData'
export default {
  name: 'OrderAdmin',
  data() {
    return {
      // timeData: [],
      total: 0,
      orderType: [],
      delOrderId: null,
      delModal: false,
      showModal: false,
      logisticsInfo: [],
      activeNames: [],
      currIndex: 1,
      itemIndex: -1,
      checkboxValue1: false,
      baseUrl: this.$baseUrl,
      goodsOrderList: [],
      queryParam: {
        page: 1,
        pageSize: 10,
        v_id: '',
        name: '',
        phone: '',
        vin_no: '',
        goods_id: '',
        brand_id: '',
        state: '',
        queryTitle: ''
      },
      tabList
    }
  },
  computed: {
    ...mapState(['centers', 'brandInfo', 'loginInfo']),
    // 公司信息
    shopComName() {
      let centers = this.centers
      return function (id) {
        let name = centers.find(item => item.id == id)?.value
        return name
      }
    },
    // 列表显示的数据
    showGoodsOrderList() {
      let temp = []
      let data = this.goodsOrderList
      let baseUrl = `${this.$baseUrl}/images/audi/library/`
      for (let i = 0; i < data.length; i++) {
        let { id, num, v_id, name, price, vin_no, wx_name, phone, state, price_paid, company_id, create_time, post_service,
          logistics_no, coupon_list, price_discount, goodsInfo: { id: infoId, category_id1, shop_title, images_kv, prepaid_price } } = data[i]
        let index = temp.findIndex(item => item.v_id === v_id)
        if (index < 0) {
          temp.push({
            id,
            myId: id,
            v_id,
            name,
            phone,
            company_id,
            price_paid,
            category_id1,
            create_time,
            time:
              new Date(create_time).getTime() +
              60 * 15 * 1000 -
              new Date().getTime(),
            vin_no,
            wx_name,
            children: [
              {
                num,
                v_id,
                price,
                state,
                id: infoId,
                shop_title,
                coupon_list,
                price_paid,
                post_service,
                category_id1,
                logistics_no,
                prepaid_price,
                price_discount,
                images_kv: `${baseUrl}${images_kv}`,
              }
            ]
          })
        } else {
          temp[index].children.push({
            num,
            v_id,
            price,
            state,
            id: infoId,
            shop_title,
            coupon_list,
            price_paid,
            post_service,
            category_id1,
            logistics_no,
            prepaid_price,
            price_discount,
            images_kv: `${baseUrl}${images_kv}`,
          })
        }
      }
      return temp
    }
  },
  methods: {
    // 订单列表
    async getGoodsOrderList(page = 1, cb) {
      this.queryParam.page = page
      const {
        data: { data, total }
      } = await goodsOrderListApi(this.queryParam)
      if (data.length) {
        this.goodsOrderList = [...this.goodsOrderList, ...data]
      } else {
        if (!flag) return false;
        uni.$showMsg("没有更多数据了!");
        flag = false;
      }
      cb && cb()
    },
    searchOrderList() {
      this.goodsOrderList = []
      this.getGoodsOrderList()
    },
    // 分类列表
    async getShopTypeCateList(temp2) {
      let { brand_id } = this.brandInfo
      const {
        data: { data, code }
      } = await getShopTypeCateListApi({
        brand_id,
        company_id: '1',
        state: '1'
      })
      if (code == 200) {
        for (let i = 0; i < temp2.length; i++) {
          for (let j = 0; j < data.length; j++) {
            if (temp2[i] == data[j].category_id1) {
              this.orderType.push(data[j].type_name)
              break
            }
          }
        }
      }
    },
    clickNum(i) {
      this.itemIndex = i
    },
    finish() {
      // console.log('finish')
      this.$refs.tabBar.onClickItem(this.currIndex, this.currIndex + 1)
      // this.itemIndex = i
    },
    // 继续支付
    async clickPay(item) {
      let { v_id, price_paid } = item
      let temp = item.children.map(item1 => item1.category_id1)
      let temp2 = [...new Set(temp)]
      this.orderType = []
      // 分类列表
      this.getShopTypeCateList(temp2)
      const [err, res] = await uni.login().catch(err => err)
      if (err || res.errMsg !== 'login:ok')
        return uni.$showMsg('获取code失败！')
      // 微信支付
      this.callUserPay(res.code, v_id, price_paid)
    },
    // 生成订单号，微信支付
    async callUserPay(code, vId, price) {
      let title = this.orderType.join(',')
      let { brand } = this.brandInfo
      let param = {
        code,
        price,
        title,
        brand,
        v_id: vId
      }
      const { data } = await userPayApi(param)
      if (data.code == 400) return uni.$showMsg(`${data.message}`)
      if (data.status != 200) return uni.$showMsg('支付订单创建失败！')
      // 发起微信支付
      let payInfo = {
        orderInfo: vId,
        provider: data.appId,
        // orderInfo: data.v_id,
        package: data.package,
        paySign: data.paySign,
        signType: data.signType,
        nonceStr: data.nonceStr,
        timeStamp: data.timeStamp,
      }
      const [err, succ] = await uni.requestPayment(payInfo)
      // 未完成支付
      if (err) {
        uni.$showMsg('订单未支付！')
      } else {
        uni.$showMsg('订单支付成功！')
        this.$refs.tabBar.onClickItem(1, 1 + 1)
      }
    },
    onClickTab(i) {
      if (i == 0) {
        this.queryParam.state = ''
      } else {
        this.queryParam.state = i
      }
      flag = true;
      this.currIndex = i
      this.goodsOrderList = []
      this.getGoodsOrderList()
    },
    // 到商品详情页
    onClickGoods(id) {
      uni.navigateTo({
        url: `/Shop/GoodsDetail?id=${id}`
      })
    },
    // 到订单详情页
    toOrderDetail(vId) {
      uni.navigateTo({
        url: `/Shop/OrderDetail?v_id=${vId}`
      })
    },
    onChange(event) {
      this.activeNames = event.detail
    },
    // 查快递信息
    async queryPostInfo(No) {
      // let param = { waybillNo: 'SF1148970949236' }
      let param = { waybillNo: `SF${No}` }
      const { data } = await fastPieceApi(param)
      if (!data.apiResultData.success) {
        return uni.$showMsg(`${data.apiResultData.errorMessage}`)
      }
      // console.log(data.apiResultData.obj)
      // 弹窗
      this.showModal = true
      this.logisticsInfo = data.apiResultData.obj.route
    },
    // 删除未支付订单号
    deleteOrder(v_id) {
      this.delModal = true
      this.delOrderId = { v_id }
    },
    async callDeleteApi() {
      const {
        data: { code, message }
      } = await groupMyGoodsDelApi(this.delOrderId)
      if (code == 200) {
        this.delModal = false
        // 调用子组件
        this.$refs.tabBar.onClickItem(2, this.currIndex)
        return uni.$showMsg(`${message}`)
      }
    },
    myUser() {
      uni.switchTab({
        url: '/pages/MyInfo'
      })
    },
    ...mapMutations(['saveCarModelDataList', 'changeGoodsState'])
  },
  // 触底事件
  onReachBottom() {
    this.queryParam.page++
    // 列表
    this.getGoodsOrderList(this.queryParam.page);
  },
  // 下拉事件
  onPullDownRefresh() {
    flag = true;
    this.goodsOrderList = []
    this.getGoodsOrderList(1, uni.stopPullDownRefresh)
  },
  watch: {
    showGoodsOrderList: {
      handler(newV, oldV) {
        for (let index = 0; index < newV.length; index++) {
          this.activeNames.push(index + '')
        }
      }
    }
  },
  onLoad(options) {
    let state = options.state - 0
    let { uuid } = this.loginInfo
    let { brand_id } = this.brandInfo
    this.queryParam.uuid = uuid
    this.queryParam.brand_id = brand_id
    // 调用子组件
    this.$refs.tabBar.onClickItem(state, state + 1)
    this.shareMixin.title = `订单管理`
    this.shareMixin.path = `/pages/Shop/ShopAdmin`
  },
  onPageScroll() {
    this.itemIndex = -1
  }
}
</script>

<style scoped lang="scss">
@import '@/styles/mixins.scss';

::v-deep .van-cell__value {
  font-size: 12px;
}

::v-deep .van-cell {
  // font-size: 12px;
  // background-color: #f8f9f8;
  // #eadeda
  // #eadedac7
  background-color: rgb(234 222 218 / 58%);
  border-radius: 8px 8px 0 0;
}

::v-deep .custom-class .van-collapse .van-hairline--top-bottom {
  padding: 20rpx;
}

::v-deep .van-collapse-item {
  margin: 30rpx auto 30rpx;
  width: 94%;
  // box-shadow: 0 2rpx 8rpx 2rpx rgba(0, 0, 0, 0.05);
  box-shadow: 0px 1px 10px 1px rgba(5, 5, 5, 0.05);
  border: 2rpx solid #f1f1f1;
  border-radius: 15%;
}

::v-deep .van-cell__title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

::v-deep .van-cell__value {
  color: #777;
}

::v-deep .van-cell__value,
::v-deep .van-cell__title {
  font-family: 'LynkcoType-Regular', 'Microsoft JhengHei'!important;
}

::v-deep .van-collapse-item__content {
  border-radius: 0 0 8px 8px;
}

.container {
  min-height: 100%;
  // background-color: #f8f9f8;
  position: relative;
  padding-bottom: 20rpx;
  background: #fafafa;

  .top_box {
    width: 100%;
    position: fixed;
    z-index: 99;
    top: 0rpx;
    left: 0;
  }

  .search {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 18rpx;
    background-color: #fff;
    border-bottom: 1px solid #eee;

    &_box {
      flex: 1;
    }

    .company_box_bottom {
      width: 90rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: $theme-color;

      .text {
        font-size: 22rpx;
      }
    }
  }

  .card {
    width: 95%;
    padding: 10px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 15rpx;
    box-shadow: $theme-shadow;
  }

  .goods_item_content_box {
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    border-radius: 15rpx;
    padding: 10rpx 2rpx;
    margin: 10rpx 0;

    // box-shadow: $theme-shadow;
    .img_box {
      width: 150rpx;
      height: 150rpx;
      border-radius: 12rpx;
      overflow: hidden;
      flex-shrink: 0;
      border: 2rpx solid rgba(0, 0, 0, 0.06);

      .img {
        width: 100%;
        height: 100%;
      }
    }

    .content_box {
      flex: 1;
      min-width: 0;
      margin-left: 20rpx;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: space-around;

      .title {
        width: 100%;
        @include goods_title();
        @include text-ellipsis();
        font-size: 30rpx;
      }

      .coupon_box {
        width: 100%;
        display: flex;

        // justify-content: space-between;
        .server {
          text-align: center;
          font-size: 24rpx;
          line-height: 38rpx;
          padding: 0rpx 6rpx;
          border-radius: 6rpx;
          color: $theme-color;
          vertical-align: middle;
          margin-right: 10rpx;
          background-color: #f1f1f1;
        }

        .server-r {
          color: #e6a23c;
          margin-left: auto;
        }

        .post {
          padding: 0rpx 6rpx !important;
          vertical-align: middle;
          @include text-tag-light();
        }

        .post__red {
          margin: 0 0 0 16rpx;
          padding: 0 6rpx;
          color: #fff;
          border: 1px solid #de4141;
          background: #de4141;
        }
      }

      .bottom_box {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: flex-end;

        .price_box {
          display: flex;
          align-items: flex-end;

          .present {
            color: $theme-color;
            font-size: 24rpx;

            .price {
              font-weight: bold;
              font-size: 30rpx;
            }
          }

          .price_paid {
            margin-left: 20rpx;
            color: #999;
            text-decoration: line-through;
            line-height: 38rpx;
            font-size: 22rpx;
          }

          .num {
            margin-right: 20rpx;
            font-size: 22rpx;
          }
        }
      }
    }
  }
}

.count-down-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .count-down__title {
    font-size: 24rpx;
    line-height: 28rpx;
    color: $theme-color;
  }
}

.order-bottom {
  margin-top: 40rpx;
  display: flex;
  // justify-content: space-between;
  // justify-content: end;
  align-items: center;

  &__box {
    display: flex;
    align-items: center;
  }

  &__pay {
    font-size: 24rpx;
    /* line-height: 32rpx; */
    border-radius: 6rpx;
    padding: 2rpx 10rpx;
    border: 1px solid $theme-color;
    color: #fff;
    background: $theme-color;
    margin-right: 30rpx;
  }

  &__total-price {
    text-align: right;

    &__price {
      font-size: 32rpx;
      color: $theme-color;
      font-weight: 600;
      font-family: 'Audi-type', 'Microsoft JhengHei' !important;
    }
  }

  // &__count-down {
  //   margin-top: 20rpx;
  //   display: flex;
  // justify-content: center;
  // justify-content: flex-end;
  // flex-wrap: wrap;
  // &__text {
  //   width: 100%;
  //   text-align: center;
  // }
  // }
}

.scroll-Y {
  height: 70vh;
}

// 滚动条样式
::v-deep ::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 3px !important;
  height: 1px !important;
  overflow: auto !important;
  background: #ccc !important;
  -webkit-appearance: auto !important;
  display: block;
}

::v-deep ::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 10px !important;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1) !important;
  background: #7b7979 !important;
}

::v-deep ::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  // box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2) !important;
  // border-radius: 10px !important;
  background: #ffffff !important;
}
</style>
